import { IUserParams } from "./../../api/user";
import { createSlice, Dispatch } from "@reduxjs/toolkit";
import { userLogin, roleGet, IRoleParams } from "@/api/user";
import { NavigateFunction } from "react-router-dom";
export interface UserInfoType {
  objectId: string;
  roleid: string;
  rolename: string;
  sessionToken: string;
  username: string;
  avatar: string;
  roleData: IRoleParams; //角色数据
}
export interface UserStateType {
  isLogin: boolean;
  isLoading: boolean;
  userInfo: UserInfoType | null;
}
let initialState: UserStateType = {
  isLogin: false,
  isLoading: false,
  userInfo: null,
};
//尝试提取本地存储数据
let uinfo =
  localStorage.getItem("userInfo") || sessionStorage.getItem("userInfo");
if (uinfo) {
  initialState.isLogin = true;
  initialState.userInfo = JSON.parse(uinfo);
}
const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    //开始登录
    loginStart(state) {
      state.isLoading = true;
    },
    //登录成功
    loginSuccess(state, action) {
      state.isLoading = false;
      state.isLogin = true;
      // console.log("登录成功", action);
      let { info, remember } = action.payload;
      state.userInfo = info;
      localStorage.setItem("remember", remember); //记录用户本地存储位置
      if (remember) {
        localStorage.setItem("userInfo", JSON.stringify(info)); //持久存储
      } else {
        sessionStorage.setItem("userInfo", JSON.stringify(info)); //会话存储
      }
    },
    //登录失败、退出登录
    loginFail(state) {
      state.isLoading = false;
      state.isLogin = false;
      state.userInfo = null;
      localStorage.removeItem("userInfo");
      sessionStorage.removeItem("userInfo");
    },
  },
});

export const { loginStart, loginSuccess, loginFail } = userSlice.actions;

//异步请求
export const userLoginAsync = (
  dispatch: Dispatch,
  params: IUserParams,
  navigate: NavigateFunction
) => {
  dispatch(loginStart()); //开始登录
  console.log("开始登录");
  setTimeout(() => {
    //测试登录流程效果
    userLogin(params)
      .then(async (res) => {
        console.log("登录成功", res);
        let role = await roleGet(res.data.roleid);
        console.log("角色数据包", role);
        dispatch(
          loginSuccess({
            info: { ...res.data, roleData: role.data },
            remember: params.remember,
          })
        ); //登录成功
        navigate("/");
      })
      .catch((err) => {
        dispatch(loginFail()); //登录失败
        console.log("登录成功", err);
      });
  }, 1000);
};

export default userSlice.reducer;
